// register center in host

var http = require('http');
var url = require('url');
var querystring = require('querystring');
var path = require('path');
var fs = require('fs');

var __record = {};
var __port = 9981;

// http://[reg_center_ip]:9981/set?name=xx&ip=xx  ==> return {200,'ok'}
// http://[reg_center_ip]:9981/get?name=xx ==> return {200,result:ip} or {200,result:undefined}
var server = http.createServer(function(req, res) {
	var reqUrl = url.parse(req.url);
	var pathname = reqUrl.pathname;
	var qs = querystring.parse(reqUrl.query);
	var name = qs.name;

	console.log(reqUrl.path, pathname, name, qs);
	res.writeHead(200, {
		'Content-type': 'application/json'
	});

	if (pathname === '/set' && name) {
		__record[name] = qs.ip;
		res.end(JSON.stringify({
			result: 'ok'
		}));
	} else if (pathname === '/get' && name) {
		var ret = {};
		res.end(JSON.stringify({
			result: __record[name]
		}));
	} else {
		res.statusCode = 404;
		res.statusMessage = 'arg error';
	}
});

server.listen(__port, function() {
	console.log('server start, bind ' + __port);
});